#ifndef __KERN_MM_PMM_H__
#define __KERN_MM_PMM_H__
#include "../inc/types.h"
#include "../libs/list.h"
#include "../libs/atomic.h"
#include "mmu.h"
#include "../debug/assert.h"
#define PPN(la) (((uint32_t)(la)) >> PTXSHIFT)

/* Flags describing the status of a page frame */
#define PG_reserved                 0       // the page descriptor is reserved for kernel or unusable
#define PG_property                 1       // the member 'property' is valid

#define PageReserved(page)          test_bit(PG_reserved, &((page)->flags))
#define SetPageProperty(page)       set_bit(PG_property, &((page)->flags))
#define PageProperty(page)          test_bit(PG_property, &((page)->flags))
#define ClearPageProperty(page)     clear_bit(PG_property, &((page)->flags))
#define ClearPageReserved(page)     clear_bit(PG_reserved, &((page)->flags))
#define SetPageReserved(page)       set_bit(PG_reserved, &((page)->flags))

#define VPT                 0xFAC00000

#define KERNBASE            0xC0000000
#define KMEMSIZE            0x38000000                  // the maximum amount of physical memory
#define KERNTOP             (KERNBASE + KMEMSIZE)

typedef uint32_t pte_t;
typedef uint32_t pde_t;

#define PADDR(kva) ({                                                   \
            uint32_t __m_kva = (uint32_t)(kva);                       \
            if (__m_kva < KERNBASE) {                                   \
                panic("PADDR called with invalid kva %08lx", __m_kva);  \
            }                                                           \
            __m_kva - KERNBASE;                                         \
        })

#define KADDR(pa) ({                                                    \
            uint32_t __m_pa = (pa);                                    \
            size_t __m_ppn = PPN(__m_pa);                               \
            if (__m_ppn >= npage) {                                     \
                panic("KADDR called with invalid pa %08lx", __m_pa);    \
            }                                                           \
            (void *) (__m_pa + KERNBASE);                               \
        })


#define le2page(le, member)                 \
    to_struct((le), struct Page, member)

#define alloc_page() alloc_pages(1)
#define free_page(page) free_pages(page, 1)

// some constants for bios interrupt 15h AX = 0xE820
#define E820MAX             20      // number of entries in E820MAP
#define E820_ARM            1       // address range memory
#define E820_ARR            2       // address range reserved
struct e820map {
    int nr_map;
    struct {
        uint64_t addr;
        uint64_t size;
        uint32_t type;
    } __attribute__((packed)) map[E820MAX];
};

struct Page {
    int ref;                        // page frame's reference counter
    uint32_t flags;                 // array of flags that describe the status of the page frame
    unsigned int property;          // the num of free block, used in first fit pm manager
    list_entry_t page_link;         // free list link
};
struct pmm_manager {
    const char *name;                                 // XXX_pmm_manager's name
    void (*init)(void);                               // initialize internal description&management data structure
                                                      // (free block list, number of free block) of XXX_pmm_manager 
    void (*init_memmap)(struct Page *base, size_t n); // setup description&management data structcure according to
                                                      // the initial free physical memory space 
    struct Page *(*alloc_pages)(size_t n);            // allocate >=n pages, depend on the allocation algorithm 
    void (*free_pages)(struct Page *base, size_t n);  // free >=n pages with "base" addr of Page descriptor structures(memlayout.h)
    size_t (*nr_free_pages)(void);                    // return the number of free pages 
    void (*check)(void);                              // check the correctness of XXX_pmm_manager 
};
typedef struct {
    list_entry_t free_list;         // the list header
    unsigned int nr_free;           // # of free pages in this free list
} free_area_t;

extern size_t npage;
extern struct Page *pages;

static inline struct Page * pa2page(uint32_t pa) {
    if (PPN(pa) >= npage) {
        panic("pa2page called with invalid pa");
    }
    return &pages[PPN(pa)];
}

static inline void set_page_ref(struct Page *page, int val) {
    page->ref = val;
}
static inline int page_ref(struct Page *page) {
    return page->ref;
}
static inline ppn_t page2ppn(struct Page *page) {
    return page - pages;
}
static inline uint32_t page2pa(struct Page *page) {
    return page2ppn(page) << PGSHIFT;
}
static inline struct Page * pte2page(pte_t pte) {
    if (!(pte & PTE_P)) {
        panic("pte2page called with invalid pte");
    }
    return pa2page(PTE_ADDR(pte));
}
static inline int page_ref_inc(struct Page *page) {
    page->ref += 1;
    return page->ref;
}
static inline int page_ref_dec(struct Page *page) {
    page->ref -= 1;
    return page->ref;
}
static inline struct Page * pde2page(pde_t pde) {
    return pa2page(PDE_ADDR(pde));
}
static inline void * page2kva(struct Page *page) {
    return KADDR(page2pa(page));
}
struct Page *get_page(pde_t *pgdir, uint32_t la, pte_t **ptep_store);

size_t nr_free_pages(void);

void free_pages(struct Page *base, size_t n);

struct Page *alloc_pages(size_t n);

pte_t * get_pte(pde_t *pgdir, uint32_t la, bool create);

int page_insert(pde_t *pgdir, struct Page *page, uint32_t la, uint32_t perm);

void tlb_invalidate(pde_t *pgdir, uint32_t la);

void page_remove(pde_t *pgdir, uint32_t la);

void print_pgdir(void);

void pmm_init(void);

#endif